import React, { useState, useEffect, useRef } from 'react';
import { useNavigate } from 'react-router-dom';
import './DiscoverPage.css';
import LiveCard from './LiveCard';
import VideoCard from './VideoCard';
import { useFollow } from '../../context/FollowContext.jsx';
import './LiveCard.css';

// 视频列表数据
const videoList = [
  {
    id: 1,
    avatar: '/6.jpg',
    username: '张三',
    likes: '7.9万',
    img: '/6.jpg',
    video: '/meinv.mp4',
    isFollow: false,
    category: ['美食', '推荐']
  },
  {
    id: 2,
    avatar: '/7.jpg',
    username: '张三',
    likes: '7.9万',
    img: '/7.jpg',
    video: '/meinv.mp4',
    isFollow: true,
    category: ['游戏', '推荐']
  },
  {
    id: 3,
    avatar: '/9.jpg',
    username: '张三',
    likes: '7.9万',
    img: '/10.jpg',
    video: '/meinv.mp4',
    isFollow: false,
    category: ['音乐', '推荐']
  },
  {
    id: 4,
    avatar: '/11.jpg',
    username: '张三',
    likes: '7.9万',
    img: '/11.jpg',
    video: '/meinv.mp4',
    isFollow: true,
    category: ['舞蹈', '推荐']
  },
  {
    id: 5,
    avatar: '/12.jpg',
    username: '张三',
    likes: '7.9万',
    img: '/12.jpg',
    video: '/meinv.mp4',
    isFollow: false,
    category: ['美食', '附近']
  },
  {
    id: 6,
    avatar: '/13.jpg',
    username: '张三',
    likes: '7.9万',
    img: '/13.jpg',
    video: '/meinv.mp4',
    isFollow: false,
    category: ['旅行', '附近']
  },
  {
    id: 7,
    avatar: '/14.jpg',
    username: '张三',
    likes: '7.9万',
    img: '/14.jpg',
    video: '/meinv.mp4',
    isFollow: true,
    category: ['时尚', '推荐']
  },
  {
    id: 8,
    avatar: '/6.jpg',
    username: '张三',
    likes: '7.9万',
    img: '/7.jpg',
    video: '/meinv.mp4',
    isFollow: false,
    category: ['宠物', '搞笑']
  },
  {
    id: 9,
    avatar: '/9.jpg',
    username: '时尚达人',
    likes: '5.2万',
    img: '/10.jpg',
    video: '/meinv.mp4',
    isFollow: false,
    category: ['时尚', '推荐']
  },
  {
    id: 10,
    avatar: '/11.jpg',
    username: '运动博主',
    likes: '8.1万',
    img: '/12.jpg',
    video: '/meinv.mp4',
    isFollow: true,
    category: ['体育', '健身']
  },
  {
    id: 11,
    avatar: '/13.jpg',
    username: '美食小当家',
    likes: '9.7万',
    img: '/14.jpg',
    video: '/meinv.mp4',
    isFollow: false,
    category: ['美食', '推荐']
  },
  {
    id: 12,
    avatar: '/6.jpg',
    username: '科技评测',
    likes: '4.3万',
    img: '/7.jpg',
    video: '/meinv.mp4',
    isFollow: true,
    category: ['科技', '推荐']
  },
  {
    id: 13,
    avatar: '/9.jpg',
    username: '插画师',
    likes: '3.5万',
    img: '/10.jpg',
    video: '/meinv.mp4',
    isFollow: false,
    category: ['时尚', '推荐']
  },
  {
    id: 14,
    avatar: '/11.jpg',
    username: '街头魔术',
    likes: '6.7万',
    img: '/12.jpg',
    video: '/meinv.mp4',
    isFollow: true,
    category: ['搞笑', '附近']
  },
  {
    id: 15,
    avatar: '/13.jpg',
    username: '亲子博主',
    likes: '4.8万',
    img: '/14.jpg',
    video: '/meinv.mp4',
    isFollow: false,
    category: ['宠物', '推荐']
  },
  {
    id: 16,
    avatar: '/6.jpg',
    username: '汽车达人',
    likes: '8.9万',
    img: '/7.jpg',
    video: '/meinv.mp4',
    isFollow: true,
    category: ['科技', '推荐']
  },
  {
    id: 17,
    avatar: '/9.jpg',
    username: '旅行博主',
    likes: '7.4万',
    img: '/10.jpg',
    video: '/meinv.mp4',
    isFollow: false,
    category: ['旅行', '推荐']
  },
  {
    id: 18,
    avatar: '/11.jpg',
    username: '健身教练',
    likes: '5.5万',
    img: '/12.jpg',
    video: '/meinv.mp4',
    isFollow: true,
    category: ['健身', '体育']
  },
  {
    id: 19,
    avatar: '/13.jpg',
    username: '舞蹈达人',
    likes: '9.2万',
    img: '/14.jpg',
    video: '/meinv.mp4',
    isFollow: false,
    category: ['舞蹈', '音乐']
  },
  {
    id: 20,
    avatar: '/6.jpg',
    username: '摄影师',
    likes: '6.3万',
    img: '/7.jpg',
    video: '/meinv.mp4',
    isFollow: true,
    category: ['旅行', '时尚']
  }
];

// 直播列表数据
const liveList = [
  {
    id: 101,
    cover: '/10.jpg',
    title: '天津 摇滚不死',
    location: '天津',
    viewer: 420,
    category: ['音乐', '推荐']
  },
  {
    id: 102,
    cover: '/11.jpg',
    title: '北京 街头艺人',
    location: '北京',
    viewer: 666,
    category: ['音乐', '推荐']
  },
  {
    id: 103,
    cover: '/12.jpg',
    title: '上海 时尚穿搭分享',
    location: '上海',
    viewer: 823,
    category: ['时尚', '推荐']
  },
  {
    id: 104,
    cover: '/13.jpg',
    title: '广州 美食探店',
    location: '广州',
    viewer: 1254,
    category: ['美食', '推荐']
  },
  {
    id: 105,
    cover: '/14.jpg',
    title: '成都 街头表演',
    location: '成都',
    viewer: 987,
    category: ['舞蹈', '推荐']
  },
  {
    id: 106,
    cover: '/6.jpg',
    title: '杭州 西湖风光',
    location: '杭州',
    viewer: 765,
    category: ['旅行', '推荐']
  },
  {
    id: 107,
    cover: '/7.jpg',
    title: '武汉 夜市美食',
    location: '武汉',
    viewer: 890,
    category: ['美食', '推荐']
  },
  {
    id: 108,
    cover: '/9.jpg',
    title: '南京 古城探秘',
    location: '南京',
    viewer: 650,
    category: ['旅行', '推荐']
  },
  {
    id: 109,
    cover: '/10.jpg',
    title: '重庆 火锅达人',
    location: '重庆',
    viewer: 1100,
    category: ['美食', '推荐']
  },
  {
    id: 110,
    cover: '/11.jpg',
    title: '苏州 园林漫步',
    location: '苏州',
    viewer: 720,
    category: ['旅行', '推荐']
  }
];

// 分类数据
const categories = [
  '推荐', '附近', '游戏', '音乐', '舞蹈', '美食', '旅行', '时尚', '宠物', '搞笑', '科技', '体育', '健身'
];

const DiscoverPage = () => {
  const navigate = useNavigate();
  const { isFollowing } = useFollow();
  const [activeTab, setActiveTab] = useState(0);
  const [activeCategory, setActiveCategory] = useState(0);
  const [refreshing, setRefreshing] = useState(false);
  const [videos, setVideos] = useState(videoList.map(video => ({
    ...video,
    isFollow: isFollowing(video.id)
  })));
  const [lives, setLives] = useState(liveList);
  const [filteredVideos, setFilteredVideos] = useState(videos);
  const [filteredLives, setFilteredLives] = useState(liveList);
  const [activeLiveIndex, setActiveLiveIndex] = useState(0);
  const [touchStartX, setTouchStartX] = useState(null);
  
  // 直播容器引用
  const liveListRef = useRef(null);

  // 当分类切换或关注状态变化时筛选视频和直播
  useEffect(() => {
    const selectedCategory = categories[activeCategory];
    
    // 筛选符合当前分类的视频，同时更新关注状态
    const newFilteredVideos = videos.filter(video => 
      video.category.includes(selectedCategory)
    ).map(video => ({
      ...video,
      isFollow: isFollowing(video.id)
    }));
    setFilteredVideos(newFilteredVideos);
    
    // 筛选符合当前分类的直播
    const newFilteredLives = lives.filter(live => 
      live.category.includes(selectedCategory)
    );
    setFilteredLives(newFilteredLives);
    
    // 重置活跃直播索引
    setActiveLiveIndex(0);
    
    // 滚动到开始位置
    if (liveListRef.current) {
      liveListRef.current.scrollLeft = 0;
    }
  }, [activeCategory, videos, lives, isFollowing]);

  // 处理刷新
  const handleRefresh = () => {
    setRefreshing(true);
    
    // 模拟刷新操作
    setTimeout(() => {
      // 随机打乱视频顺序并更新关注状态
      const shuffledVideos = [...videos]
        .sort(() => Math.random() - 0.5)
        .map(video => ({
          ...video,
          isFollow: isFollowing(video.id)
        }));
      setVideos(shuffledVideos);
      
      // 随机打乱直播顺序
      const shuffledLives = [...lives].sort(() => Math.random() - 0.5);
      setLives(shuffledLives);
      
      setRefreshing(false);
    }, 800);
  };

  // 跳转到短视频页面
  const goToShorts = () => {
    navigate('/shorts');
  };
  
  // 添加跳转到直播页面的函数
  const goToLiveList = () => {
    // 导航到直播页面，并传递当前分类
    navigate('/lives', { state: { category: categories[activeCategory] } });
  };
  
  // 添加跳转到视频列表页面的函数
  const goToVideoList = () => {
    // 导航到视频列表页面，并传递当前分类
    navigate('/videos', { state: { category: categories[activeCategory] } });
  };
  
  // 返回主页
  const goToHomepage = () => {
    navigate('/homepage');
  };
  
  // 处理直播左右滑动
  const handleLiveSwipe = (direction) => {
    const totalLives = filteredLives.length;
    if (totalLives <= 1) return;
    
    let newIndex;
    if (direction === 'left') {
      newIndex = (activeLiveIndex + 1) % totalLives;
    } else {
      newIndex = (activeLiveIndex - 1 + totalLives) % totalLives;
    }
    
    setActiveLiveIndex(newIndex);
    
    // 滚动到选中的直播卡片
    if (liveListRef.current) {
      const scrollAmount = newIndex * (liveListRef.current.clientWidth * 0.45);
      liveListRef.current.scrollTo({
        left: scrollAmount,
        behavior: 'smooth'
      });
    }
  };
  
  // 处理触摸开始
  const handleTouchStart = (e) => {
    setTouchStartX(e.touches[0].clientX);
  };
  
  // 处理触摸结束
  const handleTouchEnd = (e) => {
    if (touchStartX === null) return;
    
    const touchEndX = e.changedTouches[0].clientX;
    const diffX = touchStartX - touchEndX;
    
    // 判断滑动方向
    if (Math.abs(diffX) > 50) { // 滑动超过50px才触发
      if (diffX > 0) {
        // 向左滑
        handleLiveSwipe('left');
      } else {
        // 向右滑
        handleLiveSwipe('right');
      }
    }
    
    setTouchStartX(null);
  };
  
  // 点击导航按钮
  const handleNavClick = (direction) => {
    handleLiveSwipe(direction);
  };

  return (
    <div className="discover-page">
      {/* 头部搜索栏 */}
      <div className="discover-header">
        <div className="home-button" onClick={goToHomepage}>
          返回首页
        </div>
        <div className="search-bar" onClick={() => navigate('/search')}>
          <span className="search-icon">🔍</span>
          <input 
            type="text" 
            className="search-input" 
            placeholder="搜索视频、用户、话题" 
            readOnly
          />
        </div>
        
        {/* 分类选项卡 */}
        <div className="category-tabs">
          {categories.map((category, index) => (
            <div 
              key={index} 
              className={`category-tab ${index === activeCategory ? 'active' : ''}`}
              onClick={() => setActiveCategory(index)}
            >
              {category}
              {index === activeCategory && <div className="category-indicator"></div>}
            </div>
          ))}
        </div>
      </div>
      
      {/* 内容区域 */}
      <div className="content-section">
        {/* 直播区域 */}
        <div className="section-title">
          热门直播
          <span className="see-all" onClick={goToLiveList}>查看全部</span>
        </div>
        
        {filteredLives.length > 0 ? (
          <div className="live-swipe-container">
            <div 
              className="live-nav-button live-prev"
              onClick={() => handleNavClick('right')}
            >
              <span>❮</span>
            </div>
            
            <div 
              className="live-list" 
              ref={liveListRef}
              onTouchStart={handleTouchStart}
              onTouchEnd={handleTouchEnd}
            >
              {filteredLives.map((live, index) => (
                <div 
                  key={live.id} 
                  className={`live-card-wrapper ${index === activeLiveIndex ? 'active-live' : ''}`}
                >
                  <LiveCard live={live} />
                </div>
              ))}
            </div>
            
            <div 
              className="live-nav-button live-next"
              onClick={() => handleNavClick('left')}
            >
              <span>❯</span>
            </div>
            
            {/* 导航指示器 */}
            <div className="live-indicators">
              {filteredLives.map((_, index) => (
                <span 
                  key={index}
                  className={`live-indicator ${index === activeLiveIndex ? 'active' : ''}`}
                  onClick={() => {
                    setActiveLiveIndex(index);
                    // 滚动到对应位置
                    if (liveListRef.current) {
                      const scrollAmount = index * (liveListRef.current.clientWidth * 0.45);
                      liveListRef.current.scrollTo({
                        left: scrollAmount,
                        behavior: 'smooth'
                      });
                    }
                  }}
                />
              ))}
            </div>
          </div>
        ) : (
          <div className="empty-content">
            <div className="empty-icon">🔍</div>
            <div className="empty-text">当前分类暂无直播</div>
          </div>
        )}
        
        {/* 视频区域 */}
        <div className="section-title" style={{marginTop: '20px'}}>
          推荐视频
          <span className="see-all" onClick={goToVideoList}>查看全部</span>
        </div>
        
        {filteredVideos.length > 0 ? (
          <div className="video-grid">
            {filteredVideos.map(video => (
              <VideoCard 
                key={video.id} 
                video={video} 
                onClick={goToShorts}
              />
            ))}
          </div>
        ) : (
          <div className="empty-content">
            <div className="empty-icon">🔍</div>
            <div className="empty-text">当前分类暂无视频</div>
          </div>
        )}
      </div>
      
      {/* 刷新按钮 */}
      <div className={`refresh-btn ${refreshing ? 'refreshing' : ''}`} onClick={handleRefresh}>
        {refreshing ? '↻' : '↻'}
      </div>
    </div>
  );
};

export default DiscoverPage;
